import 'dart:io';

import 'package:flutter/material.dart';

import 'package:shop/utils/MyToast.dart';
import 'Page3.dart';
import 'Page1.dart';
import 'Page2.dart';
import 'Page4.dart';

// 首页
// by: yrs
//
class Tabs extends StatefulWidget {
  @override
  _TabsState createState() => _TabsState();
}

class _TabsState extends State<Tabs> {
  int _currentIndex = 0;
  PageController _pageController;
  List<Widget> tabs = [
    Page1(),
    Page2(),
    Page3(),
    Page4(),
  ];

  @override
  void initState() {
    super.initState();
    _pageController = new PageController(initialPage: this._currentIndex);
  }

  @override
  void dispose() {
    super.dispose();
    _pageController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: _isExit,
      child: Scaffold(
        body: PageView(
          physics: NeverScrollableScrollPhysics(),
          controller: _pageController,
          children: this.tabs,
          onPageChanged: (index) {
            setState(() {
              _currentIndex = index;
            });
          },
        ),
        bottomNavigationBar: BottomNavigationBar(
            currentIndex: this._currentIndex,
            onTap: (index) {
              setState(() {
                this._currentIndex = index;
                _pageController.jumpToPage(index);
              });
            },
            fixedColor: Colors.red,
            type: BottomNavigationBarType.fixed,
            items: [
              BottomNavigationBarItem(
                icon: Icon(Icons.home),
                title: Text("首页"),
              ),
              BottomNavigationBarItem(
                  icon: Icon(Icons.category), title: Text("分类")),
              BottomNavigationBarItem(
                  icon: Icon(Icons.shopping_cart), title: Text("购物车")),
              BottomNavigationBarItem(
                  icon: Icon(Icons.people), title: Text("我的")),
            ]),
      ),
    );
  }

  DateTime _lastTime;
  Future<bool> _isExit() {
    if (_lastTime == null ||
        DateTime.now().difference(_lastTime) > Duration(milliseconds: 2000)) {
      _lastTime = DateTime.now();
      MyToast.showBottomShortToast("再次点击退出应用");
      return Future.value(false);
    }
    MyToast.cancelToast();
    exit(0);
    return Future.value(true);
  }
}
